﻿using DotNet.Utilities;
using FriendAD.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace FriendAD.web.Controllers
{
    public class HomeController : Controller
    {

        public ActionResult Index()
        {
            return View();
        }
        
        public ActionResult a(int id=0)
        {
            if (id==0)
            {
                return Content(@"<script type='text/javascript'>alert('\u6587\u7ae0\u4e0d\u5b58\u5728\uff01');</script>");
            }
            Info info = new InfoManager().Find(id);
            if (info==null)
            {
                return Content(@"<script type='text/javascript'>alert('\u6587\u7ae0\u4e0d\u5b58\u5728\uff01');history.go(-1);</script>");
            }

            info.Count++;
            //更新浏览量信息
            new InfoManager().Update(info);

            return View(info);
        }
        public RedirectResult @goto(int id=0)
        {
            if (id==0)
            {
                RedirectToAction("index");
            }
            Info info = new InfoManager().Find(id);
            if (info == null)
            {
                RedirectToAction("index");
            }
            info.AdCount++;
            //更新浏览量信息
            new InfoManager().Update(info);
            return Redirect(info.Ad.Link);
        }
        public ActionResult About()
        {
            ViewBag.Message = "介绍页面";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "联系方式";

            return View();
        }
        [ValidateInput(false)]
        public FileContentResult img(string url="-1")
        {
            //HttpWebRequest imgreq = (HttpWebRequest)WebRequest.Create(url);
            //imgreq.Referer = "http://mp.weixin.qq.com/";
            //HttpWebRequest imgres = (HttpWebRequest)imgreq.GetResponse();

            int start = url.IndexOf("fmt=");

            //文件名处理
            string imgType= url.Substring(start+4, url.Length - start-4);


            #region 获取图片

            HttpItem item = new HttpItem();
            item.URL = url;
            item.Referer = "http://mp.weixin.qq.com/";
            item.ResultType = ResultType.Byte;

            HttpHelper helper = new HttpHelper();
            byte[] img = helper.GetHtml(item).ResultByte;
            #endregion

            
            return File(img, "image/"+ imgType + "\"");

        }
    }
}